package jvm;

import java.lang.ref.SoftReference;

/**
 * 测试软引用
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020-05-21
 */
public class SoftReferenceTest {

    public static void main(String[] args) {

//        User user = new User(10L, "jack");
//        SoftReference<User> userSoftReference = new SoftReference<>(user);
//        user = null;

        // 等价于上面三行
        SoftReference<User> userSoftReference1 = new SoftReference<>(new User(10L, "jack"));

        System.out.println(userSoftReference1.get());

        System.gc();
        // 堆空间足够 不需要对软引用回收
        System.out.println(userSoftReference1.get());

        // 10M 产生内存溢出
        try {
            byte[] bytes = new byte[1024 * 1024 * 10];
        } catch (Throwable e) {
            // OOM
            e.printStackTrace();
        } finally {
            // 在OOM 之前会回收软引用
            System.out.println(userSoftReference1.get());
        }


    }

    static class User {
        private Long no;
        private String name;

        public User(Long no, String name) {
            this.no = no;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "no=" + no +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}
